﻿/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("motobankcorp");

motobankcorp.Buckets = function(element) {
  motobankcorp.Buckets.initializeBase(this, [element]);
  this.julBuckets = null;
  this.julUsers = null;
  this.jdragClone = null;
  this._initProps({ _classInBucket: '', _classNotInBucket: '' });
}

motobankcorp.Buckets.prototype = {
  USERS_SELECTOR: ".ulUsers",
  BUCKETS_SELECTOR: ".ulBuckets",
  DRAG_CONAINER_SELECTOR: ".ColectionBuckets",
  EMPTY_USER_SELECTOR: ".user_Empty",
  USER_NAME_ATTRIBUTE: "login",
  PARENT_UL_SELECTOR: "UL:eq(0)",
  // *** Web Service
  serialize: function(jqULs) {
    var json = {};
    for (var i = 0; i < arguments.length; i++) {
      var jq = arguments[i];
      if (!jq.is(this.BUCKETS_SELECTOR)) continue;
      var bucketName = this.bucketName(jq);
      var logins = [];
      var This = this;
      jq.find("LI").each(function() {
        logins.push(This.login(this));
      });
      json[bucketName] = logins;
    }
    WSU.Users.Collection_SyncBuckets(json, _cb, this.get_wsErrorDelegate());
    function _cb(result) {
      alert("Synchronized!");
    }
  },
  // *** Drag Handlers *** 
  ulBuckets_dragBeforeStoped: function(e, ui, This) {
    var ulSrc = ui.element;
    var ulDest = ui.dest = ui.item.is("UL") ? ui.item : ui.item.parents("ul");
    if (This.cancelDrag(ulSrc, ulDest, This.jdragClone, e, ui)) return;
    if (ulDest[0] == This.julUsers[0] && This.jdragClone) This.jdragClone.remove();
  },
  ulUsers_dragBeforeStoped: function(e, ui, This) {
    var ulSrc = ui.element[0].tagName == "UL" ? ui.element : ui.element.parents("ul");
    var ulDest = ui.placeholder.parents(This.PARENT_UL_SELECTOR);
    if (This.cancelDrag(ulSrc, ulDest, This.jdragClone, e, ui)) return;
  },
  ulBuckets_dragStoped: function(e, ui, This) {
    var jqSrc = $J(this);
    This.toggleEmpty($J(this));
    var jqDest = ui.item.is("UL") ? ui.item : ui.item.parents(This.PARENT_UL_SELECTOR);
    jqDest.find("li").tsort();
    This.checkUsers();
    if (jqDest[0] != jqSrc[0]) This.serialize(jqSrc, jqDest);
  },
  ulUsers_dragStoped: function(e, ui, This) {
    var jqSrc = $J(this);
    var jqDest = ui.item.is("UL") ? ui.item : ui.item.parents(This.PARENT_UL_SELECTOR);
    jqDest.find("li").tsort();
    This.checkUsers();
    if (jqDest[0] != jqSrc[0]) This.serialize(jqDest);
  },

  // *** Initialize/Dispose ***********************************
  initialize: function() {
    motobankcorp.Buckets.callBaseMethod(this, 'initialize');
    $J("LEGEND IMG", this.julBuckets).fadeTo("fast", 0);
    $J("#Collectors", this.get_element()).resizable({
      alsoResize: "UL",
      handles: "s"
    });
    Sys.Application.add_load(Function.createDelegate(this, function() {
      $J(this.get_element()).find(this.DRAG_CONAINER_SELECTOR + ' legend').click(function() { $J(this).next().slideToggle(); });
      this.julBuckets = $J(this.BUCKETS_SELECTOR).sortable({
        beforeStop: Function.createCallback(this.ulBuckets_dragBeforeStoped, this),
        cancel: this.EMPTY_USER_SELECTOR,
        connectWith: [this.BUCKETS_SELECTOR],
        containment: this.DRAG_CONAINER_SELECTOR,
        helper: Function.createCallback(this.cloneMaybe, this),
        stop: Function.createCallback(this.ulBuckets_dragStoped, this)
      });
      this.julUsers = $J(this.USERS_SELECTOR).sortable({
        beforeStop: Function.createCallback(this.ulUsers_dragBeforeStoped, this),
        connectWith: [this.BUCKETS_SELECTOR],
        containment: this.DRAG_CONAINER_SELECTOR,
        forcePlaceholderSize: true,
        helper: Function.createCallback(this.cloneAlways, this),
        stop: Function.createCallback(this.ulUsers_dragStoped, this)
      });
      this.toggleEmpty(this.julUsers);
      this.toggleEmpty(this.julBuckets);
      this.julBuckets.add(this.julUsers).find("LI").click(Function.createCallback(function(e, This) {
        var me = this;
        if (!e.originalEvent.altKey) {
          This.julBuckets.find("LI").filter(function() {
            return This.login(this) != This.login(me);
          }).removeClass("selected").parents("UL:not(" + This.loginSelector(me) + ")").slideUp(1000);
        }
        $J(This.loginSelector(This.login(this)), This.julBuckets).toggleClass("selected").parents("UL").stop().slideDown("slow");
      }, this));
      this.julBuckets.parent("FIELDSET").find("LEGEND").droppable({
        accept: "LI",
        over: function(e, ui) {
          _fadeGarbage(this, 'over');
        },
        out: function(e, ui) {
          _fadeGarbage(this, 'out');
        },
        drop: Function.createCallback(function(e, ui, This) {
          var login = This.login(ui.draggable[0]);
          var srcElement = ui.draggable.parents("UL").eq(0);
          var groupContainer = this;
          _fadeGarbage(this, 'out');
          setTimeout(function() {
            var jq = $J(This.loginSelector(login), srcElement);
            var jqUL = jq.parents(This.PARENT_UL_SELECTOR);
            var bucketName = jq.parents("FIELDSET:eq(0)").find("LEGEND span:first").text();
            if (!confirm("Delete " + login + " from " + bucketName)) return;
            var r = jq.remove()[0];
            delete r; r = null;
            This.checkUsers();
            This.serialize(jqUL);
          }, 100);
        }, this)
      });
      function _fadeGarbage(legend, over) {
        $J("span", legend).fadeTo("fast", over == 'over' ? .2 : 1);
        if (over == 'over') $J("IMG", legend).show().fadeTo("fast", .95);
        if (over == 'out') $J("IMG", legend).fadeTo("fast", 0).hide();
      }
    }));
  },
  dispose: function() {
    //Add custom dispose actions here
    motobankcorp.Buckets.callBaseMethod(this, 'dispose');
  },
  // *** Helpers **************************************
  cancelDrag: function(ulSrc, ulDest, jClone, e, ui) {
    var cancel = ulDest.find(this.loginSelector(this.login(ui.item[0]))).get().length > 1;
    if (cancel) {
      if (jClone) jClone.remove();
      //!!!ui.cancel();
      return true;
    }
    this.toggleEmpty(ulSrc);
    this.toggleEmpty(ulDest);
  },
  toggleEmpty: function(jUL, sync) {
    var juserEmpty = jUL.find("li.user_Empty");
    if (juserEmpty.siblings("li").get().length > 0) juserEmpty.hide(); else juserEmpty.show();
  },
  clone: function(e, el, doClone, This) {
    if (!doClone && !e.originalEvent.altKey) This.jdragClone = null;
    else This.jdragClone = el.clone(true).insertAfter(el[0]);
    var elNew = el.clone(true)[0];
    elNew.style.color = "red";
    return elNew;
  },
  cloneMaybe: function(e, ui, This) { return This.clone(e, ui, undefined, This); },
  cloneAlways: function(e, ui, This) { return This.clone(e, ui, true, This); },
  checkUsers: function() {
    var This = this;
    this.julUsers.find("li").removeClass(This.get_classInBucket()).addClass(This.get_classNotInBucket());
    this.julBuckets.find("li").each(function(i) {
      This.julUsers.find(This.loginSelector(This.login(this)))
      .removeClass(This.get_classNotInBucket()).addClass(This.get_classInBucket());
    });
    //this.julUsers.tsort("li[class=" + This.get_classNotInBucket() + "]", { place: "start" });
    this.julUsers.find("LI." + This.get_classNotInBucket()).tsort({ place: "start" });
    this.julUsers.find("LI." + This.get_classInBucket()).tsort({ place: "end" });
  },
  loginSelector: function(login) {
    return String.format("li[" + this.USER_NAME_ATTRIBUTE + "='{0}']", login);
  },
  login: function(el, value) {
    if (arguments.length > 1) el.login = value;
    return el.login;
  },
  bucketName: function(jq) { return jq.parents("FIELDSET:eq(0)").find("LEGEND span:first").text(); }
}
motobankcorp.Buckets.prototype.showDeleteCollector = function() { }
motobankcorp.Buckets.registerClass('motobankcorp.Buckets', motobankcorp.UI.Control);


if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

